/**
 * JAVACC DEMO 1.0
 */
package com.apache.passport.controller;

import com.apache.action.PlatFromAction;
import com.apache.api.manager.BaseManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.database.constant.Validator;
import com.apache.database.model.Page;
import com.apache.passport.common.DesUtils;
import com.apache.passport.common.PassPortConst;
import com.apache.passport.common.PassportHelper;
import com.apache.passport.entity.OutwardSys;
import com.apache.passport.entity.SynInfo;
import com.apache.passport.entity.Token;
import com.apache.passport.manager.OutwardSysManager;
import com.apache.passport.manager.SynInfoManager;
import com.apache.tools.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:  外部系统操作类
 *
 * @author Hou Dayu 创建时间：2016-12-23
 */
@Controller
@RequestMapping({ "/passport/ssosys/" })
public class SsoSysAction extends PlatFromAction<OutwardSys> {

    @Autowired
    private OutwardSysManager outwardSysManager;

    @Autowired
    private SynInfoManager synInfoManager;

    private final String SYS_LIST = getPrefix() + "sys-list";

    private final String SYS_SAVE = getPrefix() + "sys-save";

    private final String SYS_CONSOLE = getPrefix() + "console";

    /**
     * TODO 执行用户修改之前,需要对数据进行反显,故首先获取数据值
     *
     * @see com.apache.action.PlatFromAction#edit(javax.servlet.http.HttpServletRequest, java.lang.String)
     */
    @RequestMapping({ "edit.action" })
    public ModelAndView edit(HttpServletRequest request, String sysId) {
        ParamsVo vo = new ParamsVo();
        vo.setInfoId(sysId);
        ModelAndView view = new ModelAndView(SYS_SAVE);
        OutwardSys item = (OutwardSys) outwardSysManager.getInfoById(vo);
        view.addObject("item", item);
        synInfoManager.getInfoById(vo);
        vo.setParams("sysEname", item.getSysEname());
        vo.setMethodKey("sysEnameQuery");
        ResultEntity result = (ResultEntity) synInfoManager.execute(vo);
        SynInfo synInfo = new SynInfo();
        if (!"F".equals(result.getEntity())) {
            synInfo = (SynInfo) result.getEntity();
        }

        view.addObject("item2", synInfo);
        view.addObject("isAdd", "false");
        return view;
    }

    /**
     * description:跳转至列表页
     *
     * @param request
     * @return
     */
    @RequestMapping({ "sys-list.action" })
    public ModelAndView initList(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(SYS_LIST);
        return view;
    }

    /**
     * description:  跳转至控制台界面
     *
     * @param request
     * @return
     */
    @RequestMapping({ "console.action" })
    public ModelAndView console(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(SYS_CONSOLE);
        return view;
    }

    /**
     * description:  跳转值保存页面
     *
     * @param request
     * @return
     */
    @RequestMapping({ "sys-save.action" })
    public ModelAndView syssave(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(SYS_SAVE);
        return view;
    }

    /**
     * TODO 执行用户删除操作
     *
     * @see com.apache.action.PlatFromAction#delete(javax.servlet.http.HttpServletRequest, java.lang.String)
     */
    @RequestMapping({ "del.action" })
    @ResponseBody
    public ResultMsg delete(HttpServletRequest request, String sysId) {
        ResultMsg rmsg = new ResultMsg("F", "操作失败,请重试!");
        ResultEntity result = new ResultEntity();
        SynInfo synInfo = new SynInfo();
        ParamsVo<SynInfo> synVo = new ParamsVo<SynInfo>();
        try {
            if (StrUtil.isNotNull(sysId)) {
                ParamsVo<OutwardSys> auVo = new ParamsVo<OutwardSys>();
                OutwardSys au = new OutwardSys();
                au.setSysId(sysId);
                auVo.setObj(au);
                List<OutwardSys> currSys = outwardSysManager.getList(auVo);
                if (Validator.isEmpty(currSys)) {
                    rmsg.setFlag("H");
                    rmsg.setMsg("当前系统不存在");
                } else {
                    auVo.setInfoId(sysId);
                    outwardSysManager.deleteInfo(auVo);

                    ParamsVo<SynInfo> mvo = new ParamsVo<SynInfo>();
                    mvo.setParams("sysEname", currSys.get(0).getSysEname());
                    mvo.setMethodKey("sysEnameQuery");
                    result = (ResultEntity) synInfoManager.execute(mvo);
                    if (!Validator.isEmpty(result)) {
                        if (!"K".equals(result.getEntity()) && !"F".equals(result.getEntity())) {
                            //选择内部系统后,则删除之前在同步表中的数据
                            synInfo = (SynInfo) result.getEntity();
                            synVo.setInfoId(synInfo.getSynId());
                            synVo.setObj(synInfo);
                            boolean flag = synInfoManager.deleteInfo(synVo);
                            if (!flag) {
                                rmsg.setFlag("F");
                                rmsg.setMsg("操作失败");
                                return rmsg;
                            }
                        }
                    }
                    rmsg.setFlag("T");
                    rmsg.setMsg("删除成功");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rmsg;
    }

    /**
     * description:  查询系统外部列表,并返回
     *
     * @param request
     * @return
     */
    @RequestMapping({ "list!data.action" })
    @ResponseBody
    public Object list(HttpServletRequest request, String page, String rows) {
        ParamsVo<OutwardSys> vo = new ParamsVo<OutwardSys>();
        OutwardSys outwardSys = new OutwardSys();
        if (Validator.isNotNull(request.getParameter("sysEname"))) {
            outwardSys.setSysEname(request.getParameter("sysEname"));
        }
        if (Validator.isNotNull(request.getParameter("sysCname"))) {
            outwardSys.setSysCname(request.getParameter("sysCname"));
        }
        if (Validator.isNotNull(request.getParameter("sysOwtype"))) {
            outwardSys.setSysOwtype(request.getParameter("sysOwtype"));
        }
        if (Validator.isNotNull(request.getParameter("sysStatus"))) {
            outwardSys.setSysStatus(request.getParameter("sysStatus"));
        }
        vo.setParams("pageSize", Validator.getDefaultStr(rows, "20"));
        vo.setParams("pageIndex", Validator.getDefaultStr(page, "1"));
        vo.setObj(outwardSys);
        Page pageList = outwardSysManager.getPageInfo(vo);
        Map<String, Object> mapData = new HashMap<String, Object>();
        mapData.put("total", Integer.valueOf(pageList.getCount()));
        mapData.put("rows", pageList.getPageObjects());
        return mapData;
    }

    /**
     * TODO 增加外部系统参数
     */
    @RequestMapping(value = { "/save.action" }, method = {
            org.springframework.web.bind.annotation.RequestMethod.POST })
    @ResponseBody
    public ResultMsg save(HttpServletRequest request, HttpServletResponse response,
            OutwardSys outSys) {
        //String synUseAgree, String synSeraddr, String synSockport, String synParamet
        ResultMsg rmsg = new ResultMsg("T", "操作成功!");
        String isAdd = getDefaultStr(request.getParameter("isAdd"), "true");
        ResultEntity result = null;
        ParamsVo<OutwardSys> vo = new ParamsVo<OutwardSys>();
        String cookieValue = StrUtil.doNull(PassportHelper.getInstance().getCurrCookie(request),request.getHeader("zuultokenid"));
        Token token = PassPortConst.getToken(cookieValue);

        String currEname = DesUtils.getInstance().decrypt(token.getUserEname());

        outSys.setSysAccreditename(Validator.isNull(currEname) ? "" : currEname);//添加系统人名称
        String nowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        String synParamet = request.getParameter("synParamet");
        String synSeraddr = request.getParameter("synSeraddr");
        String synSockport = request.getParameter("synSockport");
        String synUseAgree = request.getParameter("synUseAgree");
        String synId = request.getParameter("synId");

        //如果系统Id为空,则为新增,添加注册时间
        if (Validator.isNull(outSys.getSysId())) {
            outSys.setSysRegtime(nowDate);
        } else {
            //否则为更新,则添加更新时间
            outSys.setSysUpdatetime(nowDate);
            isAdd = "false";
        }

        vo.setObj(outSys);
        String id = "";
        boolean mark = false;

        //添加同步数据表
        ParamsVo<SynInfo> synVo = new ParamsVo<SynInfo>();
        SynInfo synInfo = new SynInfo();

        //outSys不为空,且isAdd为false,数据更新
        if ("false".equals(isAdd)) {
            mark = outwardSysManager.editInfo(vo);
            //数据更新分两种情况,一种是内部系统修改为外部系统,在这外部系统修改为内部系统

            //为0的时候,删除掉Syn中的数据
            if ("0".equals(outSys.getSysOwtype())) {
                ParamsVo<SynInfo> mvo = new ParamsVo<SynInfo>();
                mvo.setParams("sysEname", outSys.getSysEname());
                mvo.setMethodKey("sysEnameQuery");
                result = (ResultEntity) synInfoManager.execute(mvo);
                if (!Validator.isEmpty(result)) {
                    if (!"K".equals(result.getEntity()) && !"F".equals(result.getEntity())) {
                        //选择内部系统后,则删除之前在同步表中的数据
                        synInfo.setSynId(synId);
                        synInfo.setSysId(outSys.getSysId());
                        synVo.setInfoId(synId);
                        synVo.setObj(synInfo);
                        boolean flag = synInfoManager.deleteInfo(synVo);
                        if (!flag) {
                            rmsg.setFlag("F");
                            rmsg.setMsg("更新失败");
                            return rmsg;
                        }
                    }
                }
                //否则更新4项
            } else {
                synInfo.setSynId(synId);
                synInfo.setSysId(outSys.getSysId());
                synInfo.setSynParamet(synParamet);
                synInfo.setSynSeraddr(synSeraddr);
                synInfo.setSynSockport(synSockport);
                synInfo.setSynUseAgree(synUseAgree);
                synInfo.setSynId(synId);//设置原有的Id
                synVo.setObj(synInfo);
                synVo.setInfoId(synId);//设置主键Id
                synInfo.setSysEname(outSys.getSysEname());
                if (Validator.isNull(synId)) {
                    synInfoManager.saveInfo(synVo);
                } else {
                    boolean flag = synInfoManager.editInfo(synVo);
                    if (!flag) {
                        rmsg.setFlag("F");
                        rmsg.setMsg("更新失败");
                        return rmsg;
                    }
                }
            }
            //数据添加
        } else {
            vo.setParams("sysEname", outSys.getSysEname());
            vo.setMethodKey("outwardSysEnameQ");
            result = (ResultEntity) outwardSysManager.execute(vo);
            if (!Validator.isEmpty(result)) {
                //为空,返回SysEname为空
                if ("K".equals(result.getEntity())) {
                    rmsg.setFlag("F");
                    rmsg.setMsg(result.getMessage());
                    return rmsg;
                }
                //如果返回的对象是一个OutwardSys,则表示已经存在
                if (result.getEntity() instanceof OutwardSys) {
                    rmsg.setFlag("F");
                    rmsg.setMsg("当前系统标示已存在");
                    return rmsg;
                }
                //保存外部系统表
                id = outwardSysManager.saveInfo(vo);

                //如果是外部系统,则保存用户同步参数,如果是内部系统,则不操作此对象,因为使用的用户来源于UC
                if ("1".equals(outSys.getSysOwtype())) {
                    //增加的时候也同样添加用户信息同步
                    synInfo.setSynParamet(synParamet);
                    synInfo.setSynSeraddr(synSeraddr);
                    synInfo.setSynSockport(synSockport);
                    synInfo.setSynUseAgree(synUseAgree);
                    synInfo.setSysEname(outSys.getSysEname());
                    synInfo.setSysId(id);
                    synVo.setObj(synInfo);
                    synInfoManager.saveInfo(synVo);
                }
            }
        }

        //如果是外部系统,则保存系统参数
        if ("1".equals(outSys.getSysOwtype())) {

            synInfo.setSysEname(outSys.getSysEname());
            if ("false".equals(isAdd)) {
                synInfo.setSynId(request.getParameter("synId"));
                synInfo.setSysId(outSys.getSysId());
                synVo.setObj(synInfo);
                synInfoManager.editInfo(synVo);
            }

        } else {
            //选择内部系统后,则删除之前在同步表中的数据
            synInfo.setSynId(request.getParameter("synId"));
            synInfo.setSysId(outSys.getSysId());
            synVo.setInfoId(request.getParameter("synId"));
            synVo.setObj(synInfo);
            synInfoManager.deleteInfo(synVo);
        }

        if ((("false".equals(isAdd)) && (!(mark))) || (("true".equals(isAdd)) && (isNull(id)))) {
            rmsg.setFlag("F");
            rmsg.setMsg("操作失败！");
        }
        return rmsg;
    }

    @Override
    protected Object data(HttpServletRequest arg0, String arg1, String arg2) {
        return null;
    }

    @Override
    protected BaseManager<OutwardSys> getBaseManager() {
        return null;
    }

    @Override
    protected String getPrefix() {
        return "/passport/passport-";
    }

}
